<template>
  <div class="dataSource">
    <el-scrollbar style="height: 65vh">
      <el-divider content-position="left"> <i></i>数据来源 </el-divider>
      <el-form
        ref="form"
        :model="dataSource"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="数据库类型" prop="databaseType">
          <el-select
            v-model="dataSource.databaseType"
            clearable
            filterable
            placeholder="请选择"
            style="width: 220px"
            @change="chooseTypeEvent"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择数据源" prop="databaseId">
          <el-select
            v-model="dataSource.databaseId"
            clearable
            filterable
            placeholder="请选择"
            style="width: 220px"
          >
            <el-option
              v-for="item in databaseOptions"
              :key="item.id"
              :label="item.datasourceName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="输入数据表" prop="tableName">
          <el-input
            v-model="dataSource.tableName"
            clearable
            placeholder="请选择"
            style="width: 220px"
          ></el-input>
          <!-- <el-select
            v-model="dataSource.tableName"
            clearable
            filterable
            placeholder="请选择"
            style="width: 220px"
            @change="chooseTableEvent()"
          >
            <el-option
              v-for="item in tableOptions"
              :key="item.tableName"
              :label="item.tableName"
              :value="item.tableName"
            ></el-option>
          </el-select> -->
        </el-form-item>
      </el-form>
      <el-divider content-position="left"> <i></i>录入数据表 </el-divider>
      <div class="tableBox">
        <znxdListModify
          v-model="dataSource.tableColumnsList"
          :formColumn="selectionFormColumn"
          :initData="tablesData"
          mode="addAndDelete"
        ></znxdListModify>
      </div>
    </el-scrollbar>
    <div class="buttons" style="text-align: center; padding: 20px 0 0">
      <el-button type="primary" style="margin-left: 15px">取消</el-button>
      <el-button type="primary" style="margin-left: 15px" @click="handleConfirm"
        >确定</el-button
      >
    </div>
  </div>
</template>
<script>
import znxdListModify from "./listModify.vue"
import { typeGetDataSource } from "@/api/dataset/database.js"
import { addManualEntry, manualEntryDetail, updateManualEntry } from "@/api/manualEntry/manualEntry.js"
import { getTables, getColumnsType } from "@/api/dataset/table.js"
import { selectDictionaryByType } from "@/api/dict"
import { getDictionSelf } from "@/utils/config.js"
export default {
  components: {
    znxdListModify
  },
  data () {
    return {
      tablesData: [
      ],
      gridData: [
      ],
      defaultProps: {
        children: "children",
        label: "label"
      },
      dataSource: {},
      // 数据库类型字典
      typeOptions: [

      ],
      tableOptions: [],
      databaseOptions: [],
      page: {
        pageNo: 1, // 当前位于哪页
        pageSize: 8, // 1页显示多少条
        total: 0
      },
      selectionFormColumn: [
        {
          type: "input",
          name: "columnName",
          label: "字段名称"
        },
        {
          type: "input",
          name: "columnAliasName",
          label: "字段别名"
        },
        {
          type: "input",
          name: "columnType",
          label: "字段类型"
        },
        {
          type: "input",
          name: "columnLong",
          label: "字段长度"
        },
        // {
        //   type: "select",
        //   name: "isPrimary",
        //   label: "是否主键",
        //   options: [
        //     {
        //       label: "是",
        //       value: 1
        //     },
        //     {
        //       label: "否",
        //       value: 0
        //     }
        //   ]
        // },
        {
          type: "select",
          name: "isAuto",
          label: "是否自增",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        },
        {
          type: "select",
          name: "isNull",
          label: "允许为空",
          options: [
            {
              label: "是",
              value: 1
            },
            {
              label: "否",
              value: 0
            }
          ]
        },
        {
          type: "select",
          name: "dataSelectType",
          label: "数据选择方式",
          options: [
            {
              label: "下拉框",
              value: "1"
            },
            {
              label: "输入框",
              value: "2"
            }
          ]
        },
        {
          type: "input",
          name: "columnMemo",
          label: "数据内容"
        },
      ],
      initSelection: [],
      // 多表选择
      tableSourceData: [],
      // initTableSourceData: []
      formRules: {
        databaseType: [{ required: true, message: "不能为空" }],
        databaseId: [{ required: true, message: "不能为空" }],
        tableName: [{ required: true, message: "不能为空" }]
      }
    }
  },
  props: {
    initData: Object,
    mode: String
  },
  computed: {
  },
  watch: {
    dataSource: {
      deep: true,
      handler: function (val) {
        this.$emit("input", val)
      }
    }
  },
  methods: {
    // 点击确定
    handleConfirm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let api = this.$route.query.id ? updateManualEntry : addManualEntry
          let obj = { ...this.dataSource }
          obj.tableColumnsList[0].dataSelectType = 3
          obj.tableColumnsList[1].dataSelectType = 4
          api(obj).then((res) => {
            let data = res.data
            if (data.code == "200") {
              this.$message({
                message: data.msg,
                type: "success"
              })
              this.$router.push('/manual/entryList')
            } else {
              this.$message({
                message: data.msg,
                type: "error"
              })
            }
          })
        } else {
          return false
        }
      })

    },
    getDBType () {
      selectDictionaryByType({ type: "dbType" })
        .then((res) => {
          let data = res.data
          if (data.code === 200) {
            let options = []
            data.data.map((x) => {
              options.push({ label: x.value, value: x.value })
            })
            this.typeOptions = options
            // this.initForm();
          } else {
            // this.$message.error(data.msg);
          }
        })
        .catch(() => {
          // this.$message.error("操作失败");
        })
    },
    async chooseTypeEvent () {
      if (!this.dataSource.databaseType) { return }
      let obj = {
        tableType: this.dataSource.databaseType
      }
      await typeGetDataSource(obj).then((res) => {
        let data = res.data
        if (data.code === 200) {
          this.databaseOptions = data.content
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    async chooseTableEvent (isFirst) {
      if (!this.dataSource.tableName) { return }
      let obj = {
        datasourceId: this.dataSource.databaseId,
        tableName: this.dataSource.tableName
      }
      await getColumnsType(obj).then((res) => {
        let data = res.data
        if (data.code === 200) {
          this.tableData = data.content
          this.page.total = data.total
          if (!isFirst) {
            this.initSelection = []
          }
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    },
    handleGetSelection (data) {
      this.dataSource = {
        ...this.dataSource,
        selection: data
      }
    },
    // 校验数据
    validateForm () {
      let flag = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
          return flag
        }
      })

      if (!this.dataSource.fileType || !this.dataSource.fileName || !this.dataSource.file) {
        flag = false
        this.$message({
          message: "数据源不能为空",
          type: "error"
        })
        return flag
      }
      return flag
    },
    // 从路径获取id请求数据
    handleInitData () {
      let id = this.$route.query.id
      manualEntryDetail({ id }).then((res) => {
        console.log(res)
        let data = res.data
        if (data.code == "200") {
          let { databaseId, databaseType, tableColumnsList, tableName, id } = data.data
          this.dataSource = { databaseType, tableColumnsList, tableName, id, databaseId: parseInt(databaseId) }
          tableColumnsList[0].dataSelectType = ""
          tableColumnsList[1].dataSelectType = ""
          this.tablesData = tableColumnsList
          this.chooseTypeEvent()
        } else {
          this.$message({
            message: data.msg,
            type: "error"
          })
        }
      })
    }
  },
  mounted () {
    this.getDBType()
    this.tablesData = [{
      columnName: "regionCode"
    }, {
      columnName: "formDate"
    }]
    if (this.$route.query.id) {
      this.handleInitData()
    }
  }
};
</script>
<style lang="scss" scoped>
.dataSource {
  background: #fff;
  height: 100%;
  padding: 20px 20px 40px;
  border-radius: 3px;
  .el-divider__text.is-left {
    left: 0;
    display: flex;
    flex-direction: row;
    > i {
      display: block;
      width: 3px;
      height: 14px;
      background: #128df3;
      margin-right: 5px;
    }
  }
  .tableBox {
    padding-left: 40px;
  }
  .transfer {
    width: 600px;
    // max-height: 420px;
    // border: 1px solid red;
  }
}
</style>
<style lang="scss">
.dataSource {
  .transfer {
    .el-transfer-panel__body {
      height: 346px;
    }
    .el-transfer-panel__list {
      height: 300px;
    }
  }
}
</style>
